<?php



namespace App\Admin\Controllers;

use App\Admin\Extensions\ExcelExporter;
use App\Admin\Extensions\Tools\ImportButton;
use App\Admin\Extensions\Tools\TrashButton;
use App\Admin\Extensions\Tools\SynTask;
use App\Handlers\RedisHandler;
use App\Models\Device;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\DB;
use League\Csv\Exception;
use League\Csv\Reader;
class DeviceController extends Controller

{

    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('设备码管理');
            $content->description('');
            $content->row(view('admin.ImportPopup'));
            $content->row(view('admin.trashButton'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('设备码管理');
            $content->description('');
            $content->body($this->form()->edit($id));
        });

    }



    /**

     * Create interface.

     *

     * @return Content

     */

    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('设备码管理');
            $content->description('');
            $content->body($this->form());

        });

    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Device::class, function (Grid $grid) {
            $grid->id('ID')->sortable();
            $grid->column('sn', 'sn');
            $grid->column('udid', 'udid');
            $grid->column('bt', 'bt');
            $grid->column('imei', 'imei');
            $grid->column('wifi', 'wifi');
            $grid->column('ecid', 'ecid');
            $grid->column('tp', 'tp');
            $grid->column('nb', 'nb');
            $grid->column('reg', 'reg');
            $grid->column('num', '次数')->sortable();
            $grid->column('status', 'status')->sortable();;
//            $grid->column('status', '状态')->sortable()->display(function ($value) {
//                if($value == 0){
//                    return '<span class="badge bg-red"> 可用 </span>';
//                }elseif($value == 1){
//                    return '<span class="badge bg-orange"> 不可用 </span>';
//                }elseif($value == 2){
//                    return '<span class="badge bg-green"> 正在使用 </span>';
//                }
////                return $value == 0  ? "可用" : "不可用";
//            });
            $grid->created_at('创建时间')->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('udid', 'udid');
                $filter->equal('sn', 'sn');
                $filter->equal('bt', 'bt');
                $filter->equal('imei', 'imei');
                $filter->equal('wifu', 'wifu');
                $filter->equal('ecid', 'ecid');
                $filter->equal('tp', 'tp');
                $filter->equal('nb', 'nb');
                $filter->equal('reg', 'reg');
                $filter->between('created_at', '创建时间')->date();
            });
            $grid->tools(function ($tool) {
//                $tool->append(new SyncButton());
//                $tool->append(new ClearButton());

                $importButton = <<<EOF
        <a href="javascript:initLayer()" class="btn btn-sm btn-info">
        <i class="fa fa-cloud"></i>&nbsp;&nbsp;导入
        </a>
  
EOF;
                $tool->append($importButton);
                $tool->append(new SynTask());
            });
//            $grid->tools(function ($tool) {
//                $importButton = <<<EOF
//        <a href="javascript:initLayer()" class="btn btn-sm btn-info">
//        <i class="fa fa-cloud"></i>&nbsp;&nbsp;导入
//        </a>
//EOF;
//                $tool->append($importButton);
//                $tool->append(new SynTask());
//            });

        });

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Device::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('sn', 'sn');
            $form->text('udid', 'udid');
            $form->text('bt', 'bt');
            $form->text('imei', 'imei');
            $form->text('wifi', 'wifi');
            $form->text('ecid', 'ecid');
            $form->text('tp', 'tp');
            $form->text('nb', 'nb');
            $form->text('reg', 'reg');
            $form->text('Ethernet', 'Ethernet');
            $form->text('ICCID', 'ICCID');
//            $form->select('status', '状态')->options([
//                "可用" , "不可用","正在使用"
//            ])->default(0);
            $form->display('created_at', '创建时间');

        });

    }

    public function sync()
    {
        RedisHandler::syncDevice();
        return ['status_code' => 200, 'message' => '同步成功'];
    }

    public function trash(Device $devices)
    {
        $redis = app('redis');
        $keys =$redis->keys("device:list:*");
        if($keys){
            foreach ($keys as $key){
                $redis->del($key);
            }
        }
        $items =[];
        $hashs =$redis->keys("msg:device:*");
        if($hashs){
            foreach ($hashs as $hash){
                array_push($items,$hash);
            }
        }
        $chunks = array_chunk($items, 2000);
        $redis->pipeline(function ($pipe) use ($items){
            $pipe->del($items);
        });

        $redis -> set("maxdeid",0);
        \DB::table($devices->getTable())->truncate();
        return ['status_code' => 200, 'message' => '删除全部设备码成功'];
    }

    public function import()
    {
        ini_set('memory_limit','2048M');
        ini_set('max_execution_time',3600);
        $request = \request();
        $validFields = config('system.msg_device.export_fields');
        $file = $request->file('file');
        $items = [];
        if (!$file->isValid()) {
            return ['status_code' => 10001, 'message' => '上传失败'];
        }
        if (!in_array($file->getMimeType(), ['text/plain'])) {
            return ['status_code' => 10002, 'message' => '请上传csv文件'];
        }
        try{
            $csv = Reader::createFromPath($file->getRealPath(), 'r')->setHeaderOffset(0);
        }catch (Exception $e){
            return ['status_code' => 10003, 'message' => '读取文件失败'];
        }
        foreach ($csv as $data){
            $data = array_intersect_key($data, $validFields);
            $data['created_at'] =Carbon::now();
            array_push($items,$data);
        }
        $chunks = array_chunk($items, 2000);
        foreach ($chunks as $chunk) {
//            Device::insert($chunk);
            DB::table('device')->insert($chunk);
        }
        $added_amount = count($items);
        return ['status_code' => 200, 'message' => "新增{$added_amount}条"];
    }
}

